import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/base_state.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/bean/bank_entity.dart';
import 'package:yuan_hang_app/bean/programme_entity.dart';
import 'package:yuan_hang_app/bean/version_entity.dart';
import 'package:yuan_hang_app/http/api.dart';
import 'package:yuan_hang_app/http/http_utils.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/widget/label_item.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import 'package:yuan_hang_app/widget/w_toast.dart';

///金融计算器
class FinanceComputePage extends StatefulWidget {
  const FinanceComputePage({super.key});

  @override
  BaseState<FinanceComputePage> createState() => _FinanceComputePageState();
}

class _FinanceComputePageState extends BaseState<FinanceComputePage> {
  List<Map> modelList =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.carType);
  List<Map> versionList = [];
  List<Map> programmeList = [];
  List<Map> bankList = [];

  List<Map> monthList = [
    {"label": "12个月", "value": "12"},
    {"label": "24个月", "value": "24"},
    {"label": "36个月", "value": "36"},
    {"label": "48个月", "value": "48"},
    {"label": "60个月", "value": "60"},
  ];

  CalculatorEntity params = CalculatorEntity();

  double payRate = 15;
  GlobalKey<LabelItemState>? versionKey;
  GlobalKey<LabelItemState>? actualPriceKey;
  GlobalKey<LabelItemState>? programmeListKey;
  GlobalKey<LabelItemState>? bankListKey;
  GlobalKey<LabelItemState>? monthListKey;
  String modelId = "";
  String carModel = "";
  String carVersion = "";

  @override
  void initState() {
    super.initState();
    versionKey = GlobalKey(debugLabel: "version");
    actualPriceKey = GlobalKey(debugLabel: "actualPriceKey");
    programmeListKey = GlobalKey(debugLabel: "programmeListKey");
    bankListKey = GlobalKey(debugLabel: "bankListKey");
    monthListKey = GlobalKey(debugLabel: "monthListKey");
    modelId = getId(modelList, params.carModel);
    carModel =
        CommonReqUtils.exchangeCodeToName2(modelList, params.carModel) ?? "";
    getProgramme();
  }

  void getProgramme() {
    showLoading();
    HttpUtils().get(Api.getProgramme).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List<ProgrammeEntity> tempList = [];
        for (int i = 0; i < value.data.length; i++) {
          ProgrammeEntity p = ProgrammeEntity.fromJson(value.data[i]);
          tempList.add(p);
        }
        programmeList = ProgrammeEntity.exchangeLabelList(tempList);
        programmeListKey!.currentState
            ?.refreshList(programmeList, params.programme);
        setState(() {});
      } else {
        Toast.toast(value.errMsg);
      }
    }).catchError((err) {
      Toast.toast(err);
    });
  }

  void getBank() {
    showLoading();
    HttpUtils().get("${Api.getBank}?id=${params.programme}").then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List<BankEntity> tempList = [];
        for (int i = 0; i < value.data.length; i++) {
          BankEntity p = BankEntity.fromJson(value.data[i]);
          tempList.add(p);
        }
        bankList = BankEntity.exchangeLabelList(tempList);
        bankListKey!.currentState?.refreshList(bankList, params.banks);
        setState(() {});
      } else {
        Toast.toast(value.errMsg);
      }
    }).catchError((err) {
      Toast.toast(err);
    });
  }

  void getRate() {
    showLoading();
    HttpUtils()
        .get("${Api.getRate}?id=${params.banks}&Month=${params.month}")
        .then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        setState(() {
          params.annualizedRate = value.data["term"];
          params.simpleInterest = value.data["rate"];
        });
      } else {
        Toast.toast(value.errMsg);
      }
    }).catchError((err) {
      Toast.toast(err);
    });
  }

  void getVersionByModeId() {
    CommonReqUtils.getVersionByModeId(modelId).then((value) {
      versionList = VersionEntity.exchangeLabelList(value);
      versionKey!.currentState?.refreshList(versionList, params.carVersion);
      setState(() {});
    });
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
      title: "营销工具",
      child: ListView(
        padding: EdgeInsets.zero,
        shrinkWrap: true,
        children: [
          _opWidget(),
          StatusBtn(
            margin: EdgeInsets.symmetric(vertical: 10.px, horizontal: 30.px),
            text: "计算",
            isBg: true,
            height: 45.px,
            fontSize: WDimens.tsLabel,
            isItemBtn: true,
            onPressed: () {
              if(CalculatorEntity.checkFieldValid(params)) {
                setState(() {
                  //首付
                  params.downPayment =
                      (params.actualPrice!.toDouble() * payRate / 100).round();
                  //尾款
                  params.balancePayment =
                      params.actualPrice! - params.downPayment!;
                  //年化利率
                  double rate = params.annualizedRate! / 100;
                  //年份
                  int years = int.parse(params.month!) ~/ 12;
                  //月份
                  int months = int.parse(params.month!);
                  //总利息
                  params.totalInterest = (params.balancePayment! * rate * years).round();
                  //月还款
                  params.monthlyRepayment = ((params.balancePayment! + params.totalInterest!) / months).round();
                });
              }
            },
          ),
          _resultWidget(),
          LabelItem(
            value: "* 金融费率与月供仅供参考，部分金融方案在指定时间期限内有效，"
                "具体请以金融机构实际审批、放款、最终签约报价及车辆交付当月远航汽车发布的金融"
                "政策为准，详情可咨询远航汽车销售顾问。",
            labelType: LabelType.TEXTAREA,
            isEnabled: false,
            fontSize: 9.px,
          ),
          SizedBox(
            height: MediaQuery.of(context).padding.bottom,
          )
        ],
      ),
    );
  }

  Widget _opWidget() {
    return Container(
      margin: EdgeInsets.only(top: 1.px),
      decoration: BoxDecoration(color: WColors.white, boxShadow: [
        BoxShadow(color: WColors.CDFEFFB, blurRadius: 3.px),
      ]),
      child: Column(
        children: [
          LabelItem(
            label: "车型",
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              params.carModel = value;
              carModel =
                  CommonReqUtils.exchangeCodeToName2(modelList, value) ?? "";
              modelId = getId(modelList, value);
              getVersionByModeId();
            },
            dataList: modelList,
            value: params.carModel,
          ),
          LabelItem(
            label: "版本",
            key: versionKey,
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              params.carVersion = value;
              carVersion =
                  CommonReqUtils.exchangeCodeToName2(versionList, value) ?? "";
              setState(() {
                params.officialPrice = getPrice(versionList, value);
                params.actualPrice = getPrice(versionList, value);
                actualPriceKey?.currentState
                    ?.refreshInput(params.actualPrice.toString());
              });
            },
            dataList: versionList,
            value: params.carVersion,
          ),
          LabelItem(
            label: "官方指导价（元）",
            value: "${params.officialPrice ?? ""}",
            isEnabled: false,
          ),
          LabelItem(
            key: actualPriceKey,
            labelType: LabelType.INPUT,
            label: "实际成交价（元）",
            value: "${params.actualPrice ?? ""}",
            maxLength: 8,
            textInputType: TextInputType.number,
            onChanged: (text) {
              if (text != "" && StringUtils.isRightPrice(text)) {
                setState(() {
                  params.actualPrice = int.parse(text);
                });
              } else {
                params.actualPrice = 0;
              }
            },
          ),
          LabelItem(
            key: programmeListKey,
            label: "远航智选分期方案",
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              setState(() {
                params.programme = value;
                params.month = null;
                params.annualizedRate = null;
                params.simpleInterest = null;
                monthListKey?.currentState?.refreshList(monthList, params.month);
              });
              getBank();
            },
            dataList: programmeList,
            value: params.programme,
          ),
          LabelItem(
            key: bankListKey,
            label: "银行/金融机构",
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              setState(() {
                params.banks = value;
                params.month = null;
                params.annualizedRate = null;
                params.simpleInterest = null;
                monthListKey?.currentState?.refreshList(monthList, params.month);
              });
            },
            dataList: bankList,
            value: params.banks,
          ),
          const LabelItem(
            label: "首付比例",
            isLast: true,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Expanded(
                child: Slider(
                    value: payRate,
                    min: 0,
                    max: 100,
                    divisions: 20,
                    activeColor: WColors.primaryColor,
                    inactiveColor: WColors.CCCCCCC,
                    onChanged: (value) {
                      payRate = value;
                      setState(() {});
                    }),
              ),
              StatusBtn(
                text: "一",
                width: 28.px,
                height: 28.px,
                fontSize: 15.px,
                onPressed: () {
                  if (payRate == 0) {
                    return;
                  }
                  payRate -= 5;
                  setState(() {});
                },
              ),
              Container(
                alignment: Alignment.center,
                width: 60.px,
                padding: EdgeInsets.symmetric(horizontal: 5.px),
                child: WText(
                  "${payRate.toInt()} %",
                  style: TextStyle(
                      fontSize: WDimens.tsLabel, color: WColors.mainTextColor),
                ),
              ),
              StatusBtn(
                text: "+",
                width: 28.px,
                height: 28.px,
                fontSize: 20.px,
                onPressed: () {
                  payRate += 5;
                  if (payRate > 100) {
                    payRate = 100;
                  }
                  setState(() {});
                },
              ),
              SizedBox(
                width: 15.px,
              )
            ],
          ),
          WLine(
            height: 0.5.px,
          ),
          LabelItem(
            key: monthListKey,
            label: "融资期限",
            isLast: true,
            labelType: LabelType.DROW_DOWN,
            onSelected: (value) {
              setState(() {
                params.month = value;
              });
              if (params.programme != null && params.banks != null) {
                getRate();
              }
            },
            dataList: monthList,
            value: params.month,
          ),
        ],
      ),
    );
  }

  Widget _resultWidget() {
    return Container(
      decoration: BoxDecoration(color: WColors.white, boxShadow: [
        BoxShadow(color: WColors.CDFEFFB, blurRadius: 3.px),
      ]),
      margin: EdgeInsets.only(
        bottom: 10.px,
      ),
      child: Column(
        children: [
          Container(
            height: 45.px,
            alignment: Alignment.center,
            child: WText(
              "计算结算",
              style: TextStyle(
                fontSize: WDimens.tsLarge,
                color: WColors.mainTextColor,
              ),
            ),
          ),
          WLine(
            height: 0.5.px,
          ),
          _choosePadding(
              height: 60.px,
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Expanded(
                      child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      WText(
                        carModel,
                        style: TextStyle(
                            fontSize: WDimens.tsLabel,
                            color: WColors.mainTextColor,
                            fontWeight: FontWeight.bold),
                      ),
                      SizedBox(
                        height: 5.px,
                      ),
                      WText(
                        carVersion,
                        style: TextStyle(
                            fontSize: WDimens.tsLabel,
                            color: WColors.mainTextColor,
                            fontWeight: FontWeight.bold),
                      )
                    ],
                  )),
                  Expanded(
                      child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      WText(
                        "实际成交价（元）",
                        style: TextStyle(
                          fontSize: WDimens.tsLabel,
                          color: WColors.mainTextColor,
                        ),
                      ),
                      SizedBox(
                        height: 5.px,
                      ),
                      WText(
                        params.actualPrice == null
                            ? ""
                            : "¥${params.actualPrice}",
                        style: TextStyle(
                            fontSize: WDimens.tsLabel,
                            color: WColors.redMain,
                            fontWeight: FontWeight.bold),
                      )
                    ],
                  ))
                ],
              )),
          WLine(
            height: 0.5.px,
          ),
          _choosePadding(
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _getChooseItem(
                    "分期方案", getItemName(programmeList, params.programme)),
                _getChooseItem(
                    "银行/金融机构", getItemName(bankList, params.banks)),
              ],
            ),
          ),
          _choosePadding(
            Row(
              children: [
                _getChooseItem("首付金额",  params.downPayment == null
                    ? ""
                    : "¥${params.downPayment}"),
                _getChooseItem("首付比例", "${payRate.toInt()}%"),
              ],
            ),
          ),
          _choosePadding(
            Row(
              children: [
                _getChooseItem(
                    "融资期限（月）", StringUtils.safeGetValue(params.month)),
                const Expanded(child: SizedBox())
              ],
            ),
          ),
          WLine(
            height: 0.5.px,
          ),
          _choosePadding(
            Row(
              children: [
                _getChooseItem(
                    "年化费率",
                    params.annualizedRate == null
                        ? ""
                        : "${params.annualizedRate}%"),
                _getChooseItem(
                    "折合年化利率(单利)",
                    params.simpleInterest == null
                        ? ""
                        : "${params.simpleInterest}%"),
              ],
            ),
          ),
          WLine(
            height: 0.5.px,
          ),
          _choosePadding(
            Row(
              children: [
                _getChooseItem("融资金额", params.balancePayment == null
                    ? ""
                    : "¥${params.balancePayment}"),
                _getChooseItem("总利息", params.totalInterest == null
                    ? ""
                    : "¥${params.totalInterest}"),
              ],
            ),
          ),
          _choosePadding(
            Row(
              children: [
                _getChooseItem("月还金额", params.monthlyRepayment == null
                    ? ""
                    : "¥${params.monthlyRepayment}"),
                const Expanded(child: SizedBox())
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _getChooseItem(label, value) {
    return Expanded(
      child: Row(
        children: [
          SizedBox(
            width: 10.px,
          ),
          Expanded(
            child: WText(
              label,
              textAlign: TextAlign.start,
              style: TextStyle(
                  color: WColors.mainTextColor, fontSize: WDimens.tsLabel),
            ),
          ),
          //  SizedBox(width: 10.px,),
          WText(
            value,
            textAlign: TextAlign.end,
            style: TextStyle(
                color: WColors.mainTextColor,
                fontSize: WDimens.tsLabel,
                fontWeight: FontWeight.bold),
          ),
          SizedBox(
            width: 10.px,
          ),
        ],
      ),
    );
  }

  Widget _choosePadding(child, {double height = 40}) {
    return Container(
      height: height.px,
      alignment: Alignment.center,
      child: child,
    );
  }

  int getPrice(list, val) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]["value"] == val) {
        return double.parse(list[i]["price"].toString()).toInt();
      }
    }
    return 0;
  }

  String getItemName(list, val) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]["value"] == val) {
        return list[i]["label"].toString();
      }
    }
    return "";
  }

  String getId(list, val) {
    for (int i = 0; i < list.length; i++) {
      if (list[i]["value"] == val) {
        return list[i]["id"].toString();
      }
    }
    return "";
  }
}

class CalculatorEntity {
  String? carModel;       //车型
  String? carVersion;     //版本
  int? officialPrice;     //官方指导价
  int? actualPrice;       //实际成交价
  int? downPayment;       //首付
  int? balancePayment;    //融资金额(尾款)
  int? totalInterest;     //总利息
  int? monthlyRepayment;  //月还款
  double? annualizedRate; //年化费率
  double? simpleInterest; //单利
  String? programme;      //方案
  String? banks;          //银行
  String? month;          //融资期限

  CalculatorEntity({
    this.carModel,
    this.carVersion,
    this.officialPrice,
    this.actualPrice,
    this.downPayment,
    this.balancePayment,
    this.totalInterest,
    this.monthlyRepayment,
    this.annualizedRate,
    this.simpleInterest,
    this.programme,
    this.banks,
    this.month,
  });

  static bool checkFieldValid(CalculatorEntity entity) {
    if (entity.carModel == null) {
      Toast.toast("请选择车型");
      return false;
    }
    if (entity.carVersion == null) {
      Toast.toast("请选择版本");
      return false;
    }
    if (entity.actualPrice == null || entity.actualPrice == 0) {
      Toast.toast("请输入正确的实际成交价");
      return false;
    }
    if (entity.programme == null) {
      Toast.toast("请选择分期方案");
      return false;
    }
    if (entity.banks == null) {
      Toast.toast("请选择银行/金融机构");
      return false;
    }
    if (entity.month == null) {
      Toast.toast("请选择融资期限");
      return false;
    }
    return true;
  }
}
